package com.itheima.a20.test;

import com.itheima.a20.Yml;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.yaml.snakeyaml.Yaml;

import javax.servlet.ServletResponse;

public class YmlHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.hasMethodAnnotation(Yml.class);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

        //设置方法处理完毕
        mavContainer.setRequestHandled(true);
        ServletResponse response = webRequest.getNativeResponse(ServletResponse.class);
        // 1. 转换返回结果为 yaml 字符串
        String str = new Yaml().dump(returnValue);
        response.getWriter().write(str);



    }
}
